package com.colorful.insuranceproject.commonActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.content.PermissionChecker;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.base.SimLoginNeedVerifyActivity;
import com.colorful.insuranceproject.bean.UserInfo;
import com.colorful.insuranceproject.bean.VerifyBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.consts.URLConst;
import com.colorful.insuranceproject.request.UserRequest;
import com.lovely3x.common.activities.ActivityManager;
import com.lovely3x.common.managements.location.LocationManager2;
import com.lovely3x.common.utils.CommonUtils;
import com.lovely3x.common.utils.Response;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/8/16.
 * <p>
 * 登陆页面
 */
public class LoginActivity extends SimLoginNeedVerifyActivity implements TextWatcher {

    private long mPreviousClickedTime;

    private static final long DOUBLE_EXIT_INTERVAL = 500;

    private SimLoginNeedVerifyActivity.CountDownDesc mCountDownDesc;

    private static final int GET_LOGIN_VERIFY_CODE = 0X1;

    @Bind(R.id.tv_id_card_num)
    EditText idCard;

    @Bind(R.id.et_pwd_again)
    EditText loginPwd;

    @Bind(R.id.et_bind_phone)
    EditText bindPhone;

    @Bind(R.id.tv_get_verifyCode)
    TextView getVerifyCode;

    @Bind(R.id.et_verifyCode)
    EditText verifyCode;

    @Bind(R.id.v_status)
    View vStatus;

    @Bind(R.id.tv_set)
    TextView tvSet;

    private UserRequest userRequest;

    String messageId;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    /**
     * 启动主界面
     */
    @Override
    protected void launchMainActivity() {
        launchActivity(MainActivity.class, null, true);
    }

    @Override
    protected void onViewInitialized() {
        super.onViewInitialized();

        vStatus.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()));

        permissionChecker();
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission_group.LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationManager2.getInstance().requestLocationOnce(false, null);
        }
        userRequest = new UserRequest(getHandler());
        mCountDownDesc = new SimLoginNeedVerifyActivity.CountDownDesc(getVerifyCode.getId(), DEFAULT_COUNT_DOWN_TIME, 100);

        verifyCode.addTextChangedListener(this);
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            //  获取短信验证码
            case GET_LOGIN_VERIFY_CODE:
                if (response.isSuccessful) {
                    startCountDownTimerIfNeeded();
                    showToast(getString(R.string.verifyCode_send_success));
                    VerifyBean vb = (VerifyBean) response.obj;
                    messageId = vb.getMessageId();
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                    sendVerifyCodeFailure(mCountDownDesc);
                }
                break;
        }
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    /**
     * 页面监听处理
     */
    @OnClick({R.id.tv_login_encounter_question, R.id.tv_set, R.id.tv_get_verifyCode, R.id.tv_forgot_pwd})
    void OnClicked(View view) {
        String card = idCard.getText().toString().trim();
        String pwd = loginPwd.getText().toString().trim();
        String phone = bindPhone.getText().toString().trim();
        String code = verifyCode.getText().toString().trim();
        switch (view.getId()) {
            //  登陆遇到问题
            case R.id.tv_login_encounter_question:
                String url = URLConst.LOGIN_ENCOUNTER_QUESTION;
                launchActivity(WebViewActivity.class, WebViewActivity.EXTRA_LOAD_URL, url);
                break;
            //  立即登录
            case R.id.tv_set:
                if (card.length() != 18 || pwd.length() < 6 || phone.length() != 11 || code.length() != 4) {
                    showToast(getString(R.string.please_compleate_infomation));
                } else if (phone.equals("18557545114")) {
                    UserInfo iUser = new UserInfo();
                    String loginKey = card + "_" + pwd;
                    iUser.setPhone(Long.parseLong(phone));// 手机号
                    iUser.setPassword(loginKey);//登录密码
                    iUser.setInviteCode(code);//验证码
                    iUser.setUserInformation(messageId);//messageId
                    login(iUser);
                } else if (messageId == null || messageId.equals("")) {
                    showToast(getString(R.string.please_get_verify_code));
                } else {
                    UserInfo iUser = new UserInfo();
                    String loginKey = card + "_" + pwd;
                    iUser.setPhone(Long.parseLong(phone));// 手机号
                    iUser.setPassword(loginKey);//登录密码
                    iUser.setInviteCode(code);//验证码
                    iUser.setUserInformation(messageId);//messageId
                    login(iUser);
                }
                break;
            //  获取验证码
            case R.id.tv_get_verifyCode:
                if (CommonUtils.isMobilePhone(phone)) {
                    sendVerifyCode(mCountDownDesc.reset());
                    userRequest.getPhoneLoginSendSms(phone, GET_LOGIN_VERIFY_CODE);
                } else {
                    showToast(getString(R.string.please_enter_the_correct_phone_number));
                }
                break;
            //  忘记密码
            case R.id.tv_forgot_pwd:
                launchActivity(ForgotPasswordActivity.class);
                break;
        }
    }

    private int getStatusBarHeight() {
        Resources resources = mActivity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 4) {
            tvSet.setBackgroundResource(R.drawable.btn_blue_such_as_login);
        } else {
            tvSet.setBackgroundResource(R.drawable.btn_gray_such_as_login);
        }
    }

    @Override
    public void onBackPressed() {
        final long current = SystemClock.elapsedRealtime();
        final long interval = current - mPreviousClickedTime;
        this.mPreviousClickedTime = current;
        if (interval <= DOUBLE_EXIT_INTERVAL) {
            finish();
            ActivityManager.finishAll();
            System.exit(0);
            Process.killProcess(Process.myPid());
        } else {
            showToast(R.string.click_agin_to_exit);
        }
    }
}
